package com.su.kddq.security.security;

import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * token管理
 * </p>
 *
 * @author qy
 * @since 2019-11-08
 */
@Component
@Slf4j
public class TokenManager {

    //token过期时间：12小时
    private long tokenExpiration = 12*60*60*1000;
    private String tokenSignKey = "sxlfn1314520";

    @Autowired
    private RedisTemplate redisTemplate;

    public Map<String,String> createToken(String username,String phone) {
        Map map=new HashMap();
        String token = Jwts.builder().setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .signWith(SignatureAlgorithm.HS512, tokenSignKey).compressWith(CompressionCodecs.GZIP).compact();

        String reFresh = Jwts.builder().setSubject(phone)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey).compressWith(CompressionCodecs.GZIP).compact();
        //token续期有效时间15天
       redisTemplate.opsForValue().set(phone,reFresh,15,TimeUnit.DAYS);
       map.put("token",token);
       map.put("reFresh",reFresh);
       return map;
    }

    public String getUserFromToken(String token) {
        String user;
        try {
            user = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token).getBody().getSubject();
        } catch (ExpiredJwtException e) {
            log.error("JWT过期");
            return null;
        } catch (UnsupportedJwtException e) {
            log.error("不受支持的 Jwt 异常");
            return null;
        } catch (MalformedJwtException e) {
            log.error("格式错误的 Jwt 异常");
            return null;
        } catch (SignatureException e) {
            log.error("签名异常");
            return null;
        } catch (IllegalArgumentException e) {
            log.error("非法论证例外");
            return null;
        }
        return user;
    }

    /**
     * jwttoken无需删除，客户端扔掉即可。
     * @param token
     */
    public void removeToken(String token) {
    }

}
